package com.lagou.homework_1_4;



public class RunnableBuyTicket implements Runnable {

    //成员变量
    private int ticket;

    //有参构造
    public RunnableBuyTicket(int ticket) {
        setTicket(ticket);
    }

    //get，set方法
    public int getTicket() {
        return ticket;
    }

    public void setTicket(int ticket) {
        this.ticket = ticket;
    }

    //run方法
    @Override
    //加锁
    public synchronized void run() {

        //模拟出票
            int temp = getTicket();
            if (temp >= 1) {
                System.out.println("正在出票,请稍后..");
                temp -= 1;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("请取走您的车票！");
            } else {
                System.out.println("已经没有票了，请改乘其他车吧....");
            }
            setTicket(temp);
    }

    //测试
    public static void main(String[] args) {
        RunnableBuyTicket tbt = new RunnableBuyTicket(100);
        Thread t1 = new Thread(tbt);
        t1.start();

        Thread t2 = new Thread(tbt);
        t2.start();


        System.out.println("主线程开始等待...");


        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("剩余车票"+ tbt.getTicket()+"张！");
    }


}

